package com.yuerenjf.yuerenjinfu.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.yuerenjf.yuerenjinfu.R;
import com.yuerenjf.yuerenjinfu.activity.MainActivity;
import com.yuerenjf.yuerenjinfu.bean.LoginBean;
import com.yuerenjf.yuerenjinfu.http.Constants;
import com.yuerenjf.yuerenjinfu.http.Xutils;
import com.yuerenjf.yuerenjinfu.utils.CacheUtils;
import com.yuerenjf.yuerenjinfu.utils.CommonUtils;
import com.yuerenjf.yuerenjinfu.utils.ConstantUtils;
import com.yuerenjf.yuerenjinfu.widget.SFProgrssDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/21 0021.
 */

public class LoginFragment extends BaseFragment implements View.OnClickListener{
    private TextView tv_reg;
    private AutoCompleteTextView et_login_username;
    private EditText et_login_pwd;
    private TextView tv_login;
    private LoginBean loginBean;
    private TextView tv_forget_password;
    private String url;


    private Fragment mCurrentFragment;
    private FragmentManager fm;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        MainActivity mainActivity= (MainActivity) getActivity();
        mainActivity.setmTitleTextView("登录");
        mainActivity.setLogoImageShow(false);

    }

    @Override
    public void prepareData() {
        fm=getFragmentManager();
    }

    @Override
    public View prepareView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate( R.layout.activity_login, null);
        tv_reg = (TextView) view.findViewById(R.id.tv_reg);
        et_login_username = (AutoCompleteTextView) view.findViewById(R.id.et_login_username);
        et_login_pwd = (EditText) view.findViewById(R.id.et_login_pwd);
        tv_login = (TextView) view.findViewById(R.id.tv_login);
        tv_forget_password = (TextView) view.findViewById(R.id.tv_forget_password);

        tv_reg.setOnClickListener(this);
        tv_login.setOnClickListener(this);
        tv_forget_password.setOnClickListener(this);
        String userName = CacheUtils.getString(getActivity(), ConstantUtils.SP_USER_NAME);
        Log.e("LoginActivity", "userName---" + userName);
        if (!userName.equals("")) {
            String[] userNameArr = userName.split(",");
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity()
                    , android.R.layout.simple_list_item_1, userNameArr);
            et_login_username.setAdapter(adapter);
            et_login_username.setThreshold(1);
        }
        return view;
    }

    @Override
    public void onloadData(View view) {

    }

    @Override
    public void adapterScreen() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_reg:
//                startActivity(new Intent(this, RegisterActivity.class));
               MainActivity mainActivity= (MainActivity)getActivity();
                mainActivity.switchContent(mainActivity.getmCurrentFragment(),new RegisterFragment(),"register");
                break;
            case R.id.tv_login:
                if (!CommonUtils.isMobileNO(et_login_username.getText().toString())) {
                    Toast.makeText(getActivity(), "手机号码格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(et_login_pwd.getText().toString())) {
                    Toast.makeText(getActivity(), "密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(!CommonUtils.isPassword(et_login_pwd.getText().toString())){
                    Toast.makeText(getActivity(), "密码格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }

                getLoginData(et_login_username.getText().toString(),et_login_pwd.getText().toString());
                break;
            case R.id.tv_forget_password:
                MainActivity mainActivity2= (MainActivity)getActivity();
                Log.i("mainActivity",mainActivity2.toString());
                mainActivity2.switchContent(mainActivity2.getmCurrentFragment(),new RetrieveFragment(),"Retrieve");
//                startActivity(new Intent(this, RetrieveFragment.class));
                break;
            case R.id.ll_back:
//                finish();
                break;
        }
    }


    public void getLoginData(String phone,String pwd) {
        if(getActivity()!=null){
          final  SFProgrssDialog dialog = SFProgrssDialog.show(getActivity(),"");
            Map<String, String> map = new HashMap<>();
            map.put("phone", phone);
            map.put("password", pwd);
            Xutils.getInstance().post(getActivity(), Constants.URL_LOGIN, map,new Xutils.XCallBack() {
                @Override
                public void onResponse(String result) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    Log.e("getLoginData", result + "-----");
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        int status = jsonObject.getInt("status");
                        String message = jsonObject.getString("data");
                        if (status == 200) {
                            loginBean = new Gson().fromJson(result, LoginBean.class);

                            String uid = loginBean.getData().getUid();
                            String keep_code = loginBean.getData().getKeep_code();
                            String secret = loginBean.getData().getSecret();

                            String token = CacheUtils.getString(getActivity(), ConstantUtils.SP_TOKEN);
                            String web_signature = CommonUtils.md5(CommonUtils.md5(token) + secret);
                            List<String> stringList=new ArrayList<>();
//                        for(int i=0;i<secret.length();i++){
//                            char c=secret.charAt(i);
//                            stringList.add(c);
//                        }
//                        stringList.add(token);
//                        stringList.add(uid);
//                         Collections.sort(stringList);
                            String signature = CommonUtils.md5(CommonUtils.md5("680d76a85b1299667b5dfbe553b8c590"+uid) + secret);

                            Log.e("LoginActivity", "uid" + uid);
                            Log.e("LoginActivity", "token--" + token);
                            Log.e("LoginActivity", "secret--" + secret);
                            Log.e("LoginActivity", "CommonUtils.md5(token + uid)--" + CommonUtils.md5(token + uid));
                            Log.e("LoginActivity", "web_signature--" + web_signature);

                            CacheUtils.setString(getActivity(), ConstantUtils.SP_UID, uid);
                            CacheUtils.setString(getActivity(), ConstantUtils.SP_SECRET, secret);
                            CacheUtils.setString(getActivity(), ConstantUtils.SP_KEEP_CODE, keep_code);
                            CacheUtils.setString(getActivity(), ConstantUtils.SP_WEB_SIGNATURE, web_signature);
                            CacheUtils.setString(getActivity(), ConstantUtils.SP_SIGNATURE, signature);
                            saveUserName();


                            MainActivity mainActivity= (MainActivity) getActivity();
                            mainActivity.switchContent(mainActivity.getmCurrentFragment(),mainActivity.getContentFragment(),"login");
                            mainActivity.getContentFragment().setTabSelected(3);

//                        if (url != null) {
//                            Log.e("LoginActivity", "url--" + url);
//                            Intent intent = new Intent();
//                            intent.putExtra("url", url);
//                            LoginActivity.this.setResult(RESULT_OK, intent);
//                        }
//                        LoginActivity.this.finish();
                        } else if (status == 300) {
                            Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getActivity(), "登录失败", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailer(int status, String result) {

                }

                @Override
                public void onFinish() {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                }
            });

        }




    }

    private void saveUserName() {
        String sUserName = CacheUtils.getString(getActivity(), ConstantUtils.SP_USER_NAME);
        if (!sUserName.contains(",")) {
            sUserName = "";
        }
        if (!sUserName.contains(et_login_username.getText().toString())) {
            CacheUtils.setString(getActivity(), ConstantUtils.SP_USER_NAME, sUserName + et_login_username.getText().toString() + ",");
        }
    }

//    public void switchContent(Fragment from, Fragment to, String tag) {
//        if (mCurrentFragment != to) {
//            mCurrentFragment = to;
//            FragmentTransaction transaction = fm.beginTransaction();
//            if (!to.isAdded()) { // 先判断是否被add过
//                transaction.hide(from)
//                        .add(R.id.main_fragment, to, tag).addToBackStack(null).commit(); // 隐藏当前的fragment，add下一个到Activity中
//            } else {
//                transaction.hide(from).show(to).addToBackStack(null).commit(); // 隐藏当前的fragment，显示下一个
//            }
//        }
//    }
}
